package tcp;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 自定义HTTP服务器
 */
public class MyHTTP {

    private static final int port = 9004;

    public static void main(String[] args) throws IOException {
        //1.创建TCP服务器
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务器已经启动");

        //2.等待客户端连接
        Socket socket = serverSocket.accept();

        //3.构建读写对象
        try(BufferedReader reader =new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        ){
            //4.得到客户端信息
            String firstLine = reader.readLine();   //得到首行信息
            String[] array = firstLine.split(" ");
            String method = array[0];   //请求方法
            String url = array[1];   //url
            String httpVersion = array[2]; //http版本号

            System.out.println(String.format("方法类型：%s URL：%s HTTP版本号：%s",method,url,httpVersion));

            //5.构建返回内容
            String content = "";
            if(url.contains("404")){
                content = "<h1>没有找到此页面</h1>";
            }else if(url.contains("200")){
                content = "<h1>你好，世界</h1>";
            }

            //6.内容输出
            writer.write(String.format("%s 200 ok",httpVersion)+"\n");
            //输出head
            writer.write("Content-Type:text/html;charset=utf-8\n");
            writer.write("Content-Length:"+content.getBytes().length+"\n");
            //输出空行
            writer.write("\n");
            writer.write(content);
            writer.flush();

        }
    }

}
